package com.example.adminvue.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.adminvue.domain.*;
import com.example.adminvue.service.ISysMenuService;
import com.example.adminvue.service.LoginService;
import com.example.adminvue.utils.JwtUtil;
import com.example.adminvue.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysMenuService menuService;


    @Override
    public AjaxResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //调用登录验证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        user.setUserId(loginUser.getUser().getUserId());
        user.setNickName(loginUser.getUser().getNickName());
        user.setEmail(loginUser.getUser().getEmail());
        user.setPhonenumber(loginUser.getUser().getPhonenumber());
        user.setSex(loginUser.getUser().getSex());
        String token_str = JwtUtil.makeTokenMap(user);
        String jwt = JwtUtil.createJWT(token_str);
        //把完整的用户信息存入redis缓存
        redisCache.setCacheObject("login:"+user.getUserId(),loginUser);
        AjaxResult ajaxResult = new AjaxResult(200,"登录成功");
        Map<String,Object> map  = new HashMap<>();
        //获取权限菜单
        List<Menu> menuList = menuService.selectMenuList(loginUser);
        //封装返回数据
        map.put("token",jwt);
        map.put("expdate",JwtUtil.JWT_TTL);
        map.put("menu",menuList);
        ajaxResult.put("data",map);
        return ajaxResult;
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getUserId();

        //删除redis中的值
        String redisKey = "login:"+userid;
        redisCache.deleteObject(redisKey);
        return new ResponseResult(200,"注销成功");
    }
}
